package com.kele.ref;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

/**
 * @Version 2019
 * @Author:kele
 * @Date:2021/6/6
 * @Content:
 * @Description：
 */
public class RefTest2 {
    public static void main(String[] args) {

        Class<Cat> catClass = Cat.class;
        MyComponent annotation = catClass.getAnnotation(MyComponent.class);
        if(annotation!=null){
            try {
                Constructor<Cat> constructor = catClass.getConstructor();
                Cat cat = constructor.newInstance();

                //开始赋值
                Field[] fields = catClass.getDeclaredFields();
                for (Field field: fields
                     ) {
                    MyValue myValue = field.getAnnotation(MyValue.class);
                    if (myValue!=null){
                        Object value = myValue.value();
                        field.setAccessible(true);
                        if (field.getType().getName().equals("java.lang.Integer")){
                           value=Integer.parseInt((String) value);
                            field.set(cat,value);
                        }else {
                            field.set(cat,value);
                        }

                    }else {
                        System.out.println("没有添加了MyValue注解");
                    }
                }
                System.out.println(cat);
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        }else{
            System.out.println("无法创建对象");
        }

    }
}
